package com.server.limit.aop;

import com.server.common.exception.ErrorCode;
import com.server.common.exception.ServerException;
import com.server.limit.ILimitManager;
import com.server.limit.LimitStrategyFactory;
import com.server.limit.annotation.Limit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @author GaoYuan
 * @date 2020/12/10 15:19
 * @desc 接口限流AOP
 */
@Slf4j
@Aspect
@Configuration
public class LimitAspect {

    @Before("@annotation(com.server.limit.annotation.Limit)")
    public void before(JoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //拿limit的注解
        Limit limit = method.getAnnotation(Limit.class);
        ILimitManager limitManager = LimitStrategyFactory.get(limit.strategy());
        if(!limitManager.tryAccess(limit)) {
            throw new ServerException(ErrorCode.LOCK_LIMIT);
        }
    }

}